﻿using Microsoft.SharePoint.Client;
using Sennit.SharepointOnlineHelper.Connection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sennit.SharepointAutoMapper;

namespace Sennit.SharepointOnlineHelper.Helper
{


    public class SharepointList
    {
        public MsOnlineClaimsHelper claimsHelper;
        public string UrlApp;
        protected SharepointList() { }
        public SharepointList(SharepointAuth Auth)
        {
            claimsHelper = new MsOnlineClaimsHelper(Auth.UrlApp, Auth.Usuario, Auth.Senha);
            UrlApp = Auth.UrlApp;
        }

        public ListItemCollection GetAll(string NomeLista)
        {
            return this.Get(NomeLista, null, null);
        }


        public ListItemCollection GetById(string NomeLista, Int16 Id)
        {
            return this.Get(NomeLista, null, Id);
        }

        public ListItemCollection Get(string NomeLista, string Query, Int16? Id)
        {
            using (ClientContext context = new ClientContext(UrlApp))
            {

                context.ExecutingWebRequest += claimsHelper.clientContext_ExecutingWebRequest;

                List allergiesList = context.Web.Lists.GetByTitle(NomeLista);

                CamlQuery query = new CamlQuery() { ViewXml = Query };

                if (Id.HasValue)
                    query.ViewXml = GetCamlQueryById(Id.Value.ToString());


                

                if (string.IsNullOrEmpty(Query))
                    query = CamlQuery.CreateAllItemsQuery();

                ListItemCollection items = allergiesList.GetItems(query);

                context.Load(items);
                context.ExecuteQuery();

                return items;

            }
        }


        public ListItem NewItem(String NomeLista, Dictionary<String, String> propriedades)
        {
            using (ClientContext context = new ClientContext(UrlApp))
            {

                context.ExecutingWebRequest += claimsHelper.clientContext_ExecutingWebRequest;
                Web web = context.Web;


                List lista = web.Lists.GetByTitle(NomeLista);
                ListItemCreationInformation itemCreationInfo = new ListItemCreationInformation();
                ListItem item = lista.AddItem(itemCreationInfo);

                foreach (KeyValuePair<string, string> itemPropriedades in propriedades)
                    item[itemPropriedades.Key] = itemPropriedades.Value;

                item.Update();
                context.Load<List>(lista);
                context.Load<Microsoft.SharePoint.Client.ListItem>(item);
                context.ExecuteQuery();

                return item;
            }
        }


        public ListItem NewItem<T>(T entity) where T : IEntitySharepointMapper
        {
            using (ClientContext context = new ClientContext(UrlApp))
            {

                context.ExecutingWebRequest += claimsHelper.clientContext_ExecutingWebRequest;
                Web web = context.Web;

                
                List lista = web.Lists.GetByTitle(entity.GetSharepointListName());
                ListItemCreationInformation itemCreationInfo = new ListItemCreationInformation();
                ListItem item = lista.AddItem(itemCreationInfo);

                item.ProjectListItemFromEntity<T>(entity);

                item.Update();
                context.Load<List>(lista);
                context.Load<Microsoft.SharePoint.Client.ListItem>(item);
                context.ExecuteQuery();

                return item;
            }
        }

        public ListItem UpdateItem<T>(T entity) where T : IEntitySharepointMapper
        {
            using (ClientContext context = new ClientContext(UrlApp))
            {

                context.ExecutingWebRequest += claimsHelper.clientContext_ExecutingWebRequest;
                Web web = context.Web;


                List lista = web.Lists.GetByTitle(entity.GetSharepointListName());


                ListItem item = lista.GetItemById(entity.GetIdFromEntity());

                item.ProjectListItemFromEntity<T>(entity);

                item.Update();
                context.Load<List>(lista);
                context.Load<Microsoft.SharePoint.Client.ListItem>(item);
                context.ExecuteQuery();

                return item;
            }
        }

        private String GetCamlQueryById(string Id)
        {
            return "<View><Query><OrderBy><FieldRef Name='Title' Ascending='TRUE'></FieldRef></OrderBy><Where><Eq><FieldRef Name='ID'  ></FieldRef><Value Type='Number'>" + Id + "</Value></Eq></Where></Query></View>";
        }

        public Int16? GetItemIdByTitle(string NomeLista, string Title)
        {
            ListItemCollection items = this.Get(NomeLista, "<View><Query><OrderBy><FieldRef Name='Title' Ascending='TRUE'></FieldRef></OrderBy><Where><Eq><FieldRef Name='Title'  ></FieldRef><Value Type='Text'>" + Title + "</Value></Eq></Where></Query></View>", null);
            if (items.Count > 0)
                return Convert.ToInt16(items[0]["ID"].ToString());

            return null;

        }





    }
}
